<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/%E6%AD%A6%E6%B1%8932x32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/%E6%AD%A6%E6%B1%8916x16.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib1/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/lib1/pace/pace-theme-center-simple.min.css">
  <script src="/lib1/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"example.com","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="前言webpack本质上是一个打包工具，它会根据代码的内容解析模块依赖，帮助用户把多个模块的代码打包。 Webpack入门基础配置webpack在4.x的版本是支持零配置的，不需要使用额外的配置文件webpack.config.js就可以执行简单的构建任务。webpack的默认配置如下： 12345678const path &#x3D; require(&quot;path&quot;);module.exports &#x3D; &amp;">
<meta property="og:type" content="article">
<meta property="og:title" content="react修炼（六）-Webpack配置">
<meta property="og:url" content="http://example.com/2021/11/16/react/react%E4%BF%AE%E7%82%BC(%E5%85%AD)-Webpack%E9%85%8D%E7%BD%AE/index.html">
<meta property="og:site_name" content="Technological Blog">
<meta property="og:description" content="前言webpack本质上是一个打包工具，它会根据代码的内容解析模块依赖，帮助用户把多个模块的代码打包。 Webpack入门基础配置webpack在4.x的版本是支持零配置的，不需要使用额外的配置文件webpack.config.js就可以执行简单的构建任务。webpack的默认配置如下： 12345678const path &#x3D; require(&quot;path&quot;);module.exports &#x3D; &amp;">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-11-16T04:18:39.000Z">
<meta property="article:modified_time" content="2021-11-13T14:43:34.489Z">
<meta property="article:author" content="Li Yudong">
<meta property="article:tag" content="react初学">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://example.com/2021/11/16/react/react%E4%BF%AE%E7%82%BC(%E5%85%AD)-Webpack%E9%85%8D%E7%BD%AE/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>react修炼（六）-Webpack配置 | Technological Blog</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">Technological Blog</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">IT小白的成长之旅</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="tags fa-fw"></i>标签<span class="badge">18</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="th fa-fw"></i>分类<span class="badge">14</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="archive fa-fw"></i>归档<span class="badge">95</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

  <a href="https://github.com/tiarmor1" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2021/11/16/react/react%E4%BF%AE%E7%82%BC(%E5%85%AD)-Webpack%E9%85%8D%E7%BD%AE/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/author.jpg">
      <meta itemprop="name" content="Li Yudong">
      <meta itemprop="description" content="">
    </span>
    
    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Technological Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          react修炼（六）-Webpack配置
        </h1>
    
        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
    
              <time title="创建时间：2021-11-16 12:18:39" itemprop="dateCreated datePublished" datetime="2021-11-16T12:18:39+08:00">2021-11-16</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-11-13 22:43:34" itemprop="dateModified" datetime="2021-11-13T22:43:34+08:00">2021-11-13</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/react/" itemprop="url" rel="index"><span itemprop="name">react</span></a>
                </span>
            </span>
    
          
    
        </div>
      </header>
    
    
    
    
    <div class="post-body" itemprop="articleBody">
    
      
        <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>webpack本质上是一个打包工具，它会根据代码的内容解析模块依赖，帮助用户把多个模块的代码打包。</p>
<h1 id="Webpack入门"><a href="#Webpack入门" class="headerlink" title="Webpack入门"></a>Webpack入门</h1><h2 id="基础配置"><a href="#基础配置" class="headerlink" title="基础配置"></a>基础配置</h2><p>webpack在4.x的版本是支持零配置的，不需要使用额外的配置文件webpack.config.js就可以执行简单的构建任务。webpack的默认配置如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> path = <span class="built_in">require</span>(<span class="string">"path"</span>);</span><br><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">    entry: <span class="string">"./src/index.js"</span>,</span><br><span class="line">    output: &#123;</span><br><span class="line">        filename: <span class="string">"main.js"</span>,</span><br><span class="line">        path: path.resolve(__dirname, <span class="string">"./dist"</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>webpack默认出口entry是src/index.js；webpack的默认输出目录是./dist；webpack没有指定mode模式会出现警告，默认production生产默认。</p>
<p>配置文件:webpack.config.js。其中各个属性的基础概念如下：</p>
<p>entry入口：指定webpack执行构建任务的入口，一般为项目的入口文件；</p>
<p>output输出：告诉webpack在哪里输出它所创建的bundles，以及如何命名这些文件，默认值为./dist；</p>
<p>module模块：webpack是基于Node.js的，项目中的任何文件都可以看成module；</p>
<p>loader：模块转化器，用于对模块的源代码进行转换；</p>
<p>plugin插件：webpack的支柱功能，作用域webpack整个构建周期，plugin插件目的在于解决loader无法实现的任务；</p>
<p>bundle文件：最终打包生成的文件，比如默认配置下输出的”./dist/main.js”文件；</p>
<p>mode模式：通过配置其来制定是生产环境打包还是开发环境打包，比如：生产环境代码需要压缩，图片需要优化。</p>
<h2 id="核心配置"><a href="#核心配置" class="headerlink" title="核心配置"></a>核心配置</h2><h3 id="entry"><a href="#entry" class="headerlink" title="entry"></a>entry</h3><p>webpack的entry支持字符串、对象、数组类型，从作用上说，包括单文件入口和多文件入口两种方式。</p>
<p>单文件入口示例代码如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">    entry: <span class="string">"./src/index.js"</span></span><br><span class="line">&#125;;</span><br><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">    entry: &#123;</span><br><span class="line">        main: <span class="string">"./src/index.js"</span>,</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">    entry: [<span class="string">"./src/index.js"</span>, <span class="string">"./src/other.js"</span>],</span><br><span class="line">    output : &#123;</span><br><span class="line">        filename: <span class="string">"bundle.js"</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>上面的配置，无论是字符串还是字符数组的entry，实际上都只有一个入口，但是在打包产出上会有差异：1、如果直接是string的形式，那么webpack就会直接把该string指定的模块作为入口模块；2、如果是数组[string]的形式，那么webpack会自动生成另外一个入口模块，并将数组每个元素指定的文件加载进来，并将最后一个模块的module.exports作为入口模块的module.exports导出。</p>
<p>多文件入口示例代码：是使用对象方式配置entry</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">    entry : &#123;</span><br><span class="line">        index: <span class="string">"./src/index.js"</span>,</span><br><span class="line">        list: <span class="string">"./src/list.js"</span>,</span><br><span class="line">        detail: <span class="string">"./src/detail.js"</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="comment">//上面的语法将entry分为了三个独立的入口文件，这样会打包出来3个对应的bundle文件</span></span><br></pre></td></tr></table></figure>

<h3 id="output"><a href="#output" class="headerlink" title="output"></a>output</h3><p>webpack的output是指定了entry对应文件编译打包后的输出bundle。output的常用属性如下：1、path：设置输出的bundle文件存放路径；2、filename：设置bundle文件的名称。当不设置output时，默认输出到dist.main.js。即output.pah是dist，output.filename是main.js。</p>
<p>一份webpack的配置可以多入口，但不能多出口。对于不同的entry可以通过output.filename占位符语法来区分。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">    entry : &#123;</span><br><span class="line">        index: <span class="string">"./src/index.js"</span>,</span><br><span class="line">        list: <span class="string">"./src/list.js"</span>,</span><br><span class="line">        detail: <span class="string">"./src/detail.js"</span></span><br><span class="line">    &#125;,</span><br><span class="line">    output: &#123;</span><br><span class="line">        path: path.resolve(__dirname, <span class="string">"./build"</span>);</span><br><span class="line">        filename: <span class="string">"[name]-[hash:8].js"</span></span><br><span class="line">    &#125;,</span><br><span class="line">    mode: <span class="string">"development"</span>,</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>其中[name]，[hash:8]就是占位符，占位符是可以组合使用的；[name]：把入口配置的key作为输出模块的名称；[hash]：是整个项目的hash值，其根据每次编译内容计算得到，每次编译之后都会生成新的hash，即修改任何文件都会导致所有文件的hsah发生改变。</p>
<h3 id="module"><a href="#module" class="headerlink" title="module"></a>module</h3><p>webpack默认只支持解析Js和Json模块，对于别的类型模块，webpack默认不支持，这个时候就需要module配置了，不同的模块需要需要不同的loader来处理。module有以下两个配置：</p>
<p>module.noParse：配置项可以让webpack忽略对部分没采用模块化的文件的递归解析和处理，这样做的好处是能提高构建性能。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> path = <span class="built_in">require</span>(<span class="string">"path"</span>);</span><br><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">    <span class="built_in">module</span>: &#123;</span><br><span class="line">        noParse: <span class="regexp">/jquery |lodash/</span>,</span><br><span class="line">    &#125;,</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>module.rules：是在处理模块时，将符合规则条件的模块，提交给对应的处理器来处理，通常用来配置loader，其类型是一个数组，数组里每一项都描述了如何去处理部分文件。我们常用条件匹配方式来匹配模块，条件匹配相关的配置常用的有test、include、exclude。示例代码如下：（匹配的条件为：来自src和test文件夹，不包含node_modules和bower_modules子目录，模块的文件路径为.tsx和.jsx结尾的文件）。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> path = <span class="built_in">require</span>(<span class="string">"path"</span>);</span><br><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">    <span class="built_in">module</span>: &#123;</span><br><span class="line">        rules:[</span><br><span class="line">            &#123;</span><br><span class="line">                test: [<span class="regexp">/\.jsx?$/</span>, /\.tsx?$/],</span><br><span class="line">                include: [</span><br><span class="line">                    path.resolve(__dirname, <span class="string">'src'</span>),</span><br><span class="line">                    path.resolve(__dirname, <span class="string">'test'</span>)</span><br><span class="line">                ],</span><br><span class="line">                exclude: [</span><br><span class="line">                    path.resolve(__dirname, <span class="string">'node_modules'</span>),</span><br><span class="line">                    path.resolve(__dirname, <span class="string">'bower_modules'</span>)</span><br><span class="line">                ]</span><br><span class="line">            &#125;</span><br><span class="line">        ]</span><br><span class="line">    &#125;,</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h3 id="loader"><a href="#loader" class="headerlink" title="loader"></a>loader</h3><p>loader是模块解析器，用在module.rules字段中，配合条件匹配，对符合条件的模块进行转换。在使用对应的loader之前，需要先将其安装，例如:less-loader。先安装less-loader，再指定配置。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">    <span class="built_in">module</span>: &#123;</span><br><span class="line">        rules: [</span><br><span class="line">            test: <span class="regexp">/\.less $/</span>,</span><br><span class="line">            use: <span class="string">'less-loader'</span></span><br><span class="line">        ]</span><br><span class="line">    &#125;,</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>test项使用/.less $/正则匹配需要处理的模块文件，然后都交给less-loader来处理，这里的less-loader是个string，最终会被作为require()的参数来直接使用。这样less文件都会被less-loader处理成对应的css文件。</p>
<p>有css-loader就可以识别CSS语法了；还需要style-loader将css-loader打包好的代码以<style>的形式插入到HTML文件中。</p>
<h3 id="plugin"><a href="#plugin" class="headerlink" title="plugin"></a>plugin</h3><p>plugin是webpack的重要组成部分，通过plugin来处理loader处理不了的内容。</p>
<h3 id="devtool"><a href="#devtool" class="headerlink" title="devtool"></a>devtool</h3><p>devtool来控制怎么显示sourcemap，通过sourcemap可以快速还原代码的错误位置。但由于sourcemap包含的数据量较大，而且生成算法需要一定的计算量支持，不同的值会明显影响到构建和重新构建的速度。 </p>
<h2 id="工程化配置"><a href="#工程化配置" class="headerlink" title="工程化配置"></a>工程化配置</h2><h3 id="静态资源管理"><a href="#静态资源管理" class="headerlink" title="静态资源管理"></a>静态资源管理</h3><p>前端项目离不开各种静态资源，静态资源指的是前端中常用的图片、富媒体、字体文件等。webpack中静态资源也是可以作为模块直接使用的。这里有两个loader需要借助使用：file-loader和url-loader。</p>
<p>file-loader：能够根据配置项复制使用到的资源(不局限于图片)到构建后的文件夹，并且能改变对应的链接。</p>
<p>url-loader：包含fiale-loader的全部功能，并且能够根据配置将符合配置的文件转换成Base64方式引入，将小体积的图片Base64引入项目可以减少http请求。</p>
<h3 id="本地开发环境配置"><a href="#本地开发环境配置" class="headerlink" title="本地开发环境配置"></a>本地开发环境配置</h3><p>经过上面的步骤，项目已经支持了样式和静态文件资源，但目前对修改代码后做调试时非常不方便，需要启动webpack，手动刷新浏览器。这里我们可以使用webpack-dev-server，这是一个基于Express的本地开发服务器，它使用webpack-dev-middleware中间件来为webpack打包生成的资源文件提供web服务。</p>
<p>执行webpack-dev-server命令后，它会读取webpack的配置文件，然后将文件打包到内存中，这时打开server的默认地址:localhost:8080就可以看到文件目录或页面。可以把webpack-dev-server放到package.json的scripts中。</p>
<p>1、自动刷新功能：用户希望边写代码，边看到页面的更新情况。webpack-dev-server提供的自动刷新功能有两种模式：iframe模式：页面被放到一个iframe中，当变化时会重新加载；incline模式：将webpack-dev-server的重载代码添加到产出的bundle中。</p>
<p>两种模式都支持模块热替换，其好处是只替换更新的部分，而不是整个页面重新加载。</p>
<p>2、模块热替换：HMR。</p>
<p>3、proxy：代理。在实际开发中，本地开发服务器是不会直接请求线上数据接口的，这是因为浏览器的同源安全策略导致的跨域问题，可以使用的vServer.proxy来解决本地开发跨域的问题。</p>
<h2 id="Babel"><a href="#Babel" class="headerlink" title="Babel"></a>Babel</h2><p>Babel可以把最新的ES语法的代码轻松转换成任意版本的JavaScript语法。Babel会在正在被转义的文件当前目录中查找一个.babelrc文件。如果不存在则会向外层目录遍历树，或有一个”babel”的package.json文件。</p>
<p> babel-loader是webpack与babel的通信桥梁，不会把es6语法转换成es5，这部分工作由@babel-preset-env来完成。</p>
<p>同样，我们还可以使用Babel-polyfill，按需引入垫片，对需要的项进行转译。</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//.babelrc</span></span><br><span class="line">&#123;</span><br><span class="line">    presets : [</span><br><span class="line">        "@babel/preset-env",</span><br><span class="line">        &#123;</span><br><span class="line">            target: &#123;</span><br><span class="line">                edge: "17",</span><br><span class="line">                firefox: "60",</span><br><span class="line">                chrome: "67",</span><br><span class="line">                safari: "11.1"</span><br><span class="line">            &#125;,</span><br><span class="line">            core.js: 2,//新版本需要指定核心库版本</span><br><span class="line">            useBuiltIns: "usage" //按需注入polyfill</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="string">"@babel/preset-react"</span><span class="comment">//在webpack中安装babel与react转换的插件，继承React开发环境。</span></span><br><span class="line">    ]</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//webpack.config.js</span></span><br><span class="line">&#123;</span><br><span class="line">    test: /\.js $/,</span><br><span class="line">    exclude: /node_modules/,</span><br><span class="line">    loader: "babel-loader"</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="扩展优化"><a href="#扩展优化" class="headerlink" title="扩展优化"></a>扩展优化</h2><h3 id="配置优化"><a href="#配置优化" class="headerlink" title="配置优化"></a>配置优化</h3><p>1、缩小文件范围：loader是个值得优化的部分，应该尽可能少地使用loader，可以通过exclude、include配置来确保转译尽可能少的文件。exclude指定要排除的文件,include指定要包含的文件。</p>
<p>exclude的优先级高于include，在include和exclude中使用绝对路径数组，尽量避免exclude更倾向于使用include。</p>
<p>2、优化Resolve.modules配置，用于配置webpack去哪些目录下寻找第三方模块，默认是[‘node_modules’]；如果没有找到，就会递归的方式往父级目录的node_modules文件夹下面找；如果第三方模块都安装在了项目根目录下，就可以直接指明这个路径，不用再去一个个寻找；</p>
<p>3、优化Resolve.alias配置：通过别名来将原导入路径映射成一个新的导入路径2，以React为例，引入的React库一般存在两套代码：cjs格式，采用commonJS规范的模块化代码；umd格式，已经打包好的完整代码，没有采用模块化，可以直接执行。</p>
<p>默认情况下，webpack会从入口文件./node_modules/bin/react/index开始递归解析和处理依赖的文件。可以直接指定文件，避免此处的耗时。</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">alias: &#123;</span><br><span class="line">    "@": path.join(__dirname, "./pages"),</span><br><span class="line">    react: path.resolve(__dirname, "./node_modules/react/umd/react.production.min.js"),</span><br><span class="line">    "react-dom": path.resolve(__dirname, "./node_modules/react-dom/umd/react-dom.production.min.js")</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>4、优化Resolve.extension配置。</p>
<p>Resolve.extension在导入语句没带文件格式后置时，webpack会去Resolve.extension数组泪飙中查找，会消耗事时间，因此使用模块导入时需要加上文件格式后缀。</p>
<h3 id="资源文件优化"><a href="#资源文件优化" class="headerlink" title="资源文件优化"></a>资源文件优化</h3><p>1、开启CDN引入，动静分离，将静态资源部署在CDN服务器上。</p>
<p>2、样式文件处理：如果不做抽取配置，css文件是直接打包进js文件里的，我们希望能单独生成css文件，这样的话,css和js可以并行下载，提高页面的加载速度。</p>
<p>我们这里借助MiniCssExtractPlugin完成抽离css；借助potimize-css-assets-webpack-plugin，cssnano，减少体积。</p>
<p>3、html文件处理：借助html-webpack-plugin插件可以完成对html文件体积的压缩；</p>
<h3 id="代码优化"><a href="#代码优化" class="headerlink" title="代码优化"></a>代码优化</h3><p>1、tree-shaking：JS中tree-shaking只支持ES module的引入方式。Dead Code代码的特点：1、代码不会被执行、不可到达；2、代码执行的结果不会被用到；3、代码只会影响死的变量(只读不写)。</p>
<p>开启摇树功能后，虽然可以压缩代码体积，但是会产生一定的副作用，比如在index.js入口模块中引入图片模块、样式模块，但这些模块没有在语句中用到，但这些模块没有在语句中被用到，因此会被摇掉，此时需要修改package.json模块，避免副作用产生。或者在数组里排除不需要tree-shaking的模块。</p>
<p>2、代码分割：设置splitChunks.chunks = all；</p>
<p>3、使用HardSourceWebpackPlugin缩短构建时间。</p>

    </div>
    
    
    
    
    <div>
      
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

      
    </div>
        <div class="reward-container">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/images/alipay.png" alt="Li Yudong 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>

        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>Li Yudong
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://example.com/2021/11/16/react/react%E4%BF%AE%E7%82%BC(%E5%85%AD)-Webpack%E9%85%8D%E7%BD%AE/" title="react修炼（六）-Webpack配置">http://example.com/2021/11/16/react/react修炼(六)-Webpack配置/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

    
      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/react%E5%88%9D%E5%AD%A6/" rel="tag"># react初学</a>
          </div>
    
        

    
        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2021/11/14/react/react%E4%BF%AE%E7%82%BC(%E4%BA%94)-React%E6%BA%90%E7%A0%81/" rel="prev" title="react修炼（五）-React源码">
      <i class="fa fa-chevron-left"></i> react修炼（五）-React源码
    </a></div>
      <div class="post-nav-item">
    <a href="/2021/11/20/%E7%9B%92%E9%A9%AC%E6%8A%80%E6%9C%AF%E6%A0%88%E5%88%9D%E5%AD%A6/Rax%E5%88%9D%E5%AD%A6/" rel="next" title="Rax初学">
      Rax初学 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Webpack入门"><span class="nav-number">2.</span> <span class="nav-text">Webpack入门</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#基础配置"><span class="nav-number">2.1.</span> <span class="nav-text">基础配置</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#核心配置"><span class="nav-number">2.2.</span> <span class="nav-text">核心配置</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#entry"><span class="nav-number">2.2.1.</span> <span class="nav-text">entry</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#output"><span class="nav-number">2.2.2.</span> <span class="nav-text">output</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#module"><span class="nav-number">2.2.3.</span> <span class="nav-text">module</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#loader"><span class="nav-number">2.2.4.</span> <span class="nav-text">loader</span></a></li></ol></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Li Yudong"
      src="/images/author.jpg">
  <p class="site-author-name" itemprop="name">Li Yudong</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">95</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">14</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">18</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/tiarmor1" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;tiarmor1" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:1157019137@qq.com" title="E-Mail → mailto:1157019137@qq.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>
  <div class="cc-license motion-element" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2020 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Li Yudong</span>
</div>

        








      </div>
    </footer>
  </div>

  
  
  <script color='0,0,0' opacity='0.5' zIndex='-1' count='150' src="/lib1/canvas-nest/canvas-nest.min.js"></script>
  <script src="/lib1/anime.min.js"></script>
  <script src="/lib1/velocity/velocity.min.js"></script>
  <script src="/lib1/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>













  

  

  
   <canvas class="fireworks" style="position: fixed;left: 0;top: 0;z-index: 1; pointer-events: none;" ></canvas> 
   <script type="text/javascript" src="//cdn.bootcss.com/animejs/2.2.0/anime.min.js"></script> 
   <script type="text/javascript" src="/js/fireworks.js"></script>
  
</body>
</html>

